/**
 * Copyright (C), 2012-2018, 联奕科技有限公司
 * FileName: AbstractValidateCodeProcessor
 * Author:   石贵武
 * Date:     2018\3\12 0012 11:51
 * Description: 抽象类，验证码处理器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zhoudongxiu.security.core.vaildators.processor.impl;

import com.zhoudongxiu.security.core.enums.ValidateCodeType;
import com.zhoudongxiu.security.core.vaildators.code.ValidateCode;
import com.zhoudongxiu.security.core.vaildators.exception.ValidateCodeException;
import com.zhoudongxiu.security.core.vaildators.generator.ValidateCodeGenerator;
import com.zhoudongxiu.security.core.vaildators.processor.ValidateCodeProcessor;
import com.zhoudongxiu.security.core.vaildators.repository.ValidateCodeRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.Map;

/**
 * 〈一句话功能简述〉<br> 
 * 〈抽象类，验证码处理器〉
 *
 * @author 石贵武
 * @create 2018\3\12 0012
 * @since 1.0.0
 */
public abstract class AbstractValidateCodeProcessor<C extends ValidateCode>  implements ValidateCodeProcessor {

    /**
     * 收集系统所有的校验接口
     *
     * @Date: 2018\3\12 0012 12:53
     */
    @Autowired
    private Map<String, ValidateCodeGenerator> validateCodeGeneratorMap;

    @Autowired
    private ValidateCodeRepository validateCodeRepository;


    @Override
    public void create(ServletWebRequest request) throws Exception {
        C validateCode = this.generate(request);
        this.save(request, validateCode);
        send(request, validateCode);
    }

    @Override
    public void validate(ServletWebRequest request) {
        ValidateCodeType codeType = getValidateCodeType(request);

        C codeInSession = (C) validateCodeRepository.get(request, codeType);

        String codeInRequest;
        try {
            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),
                    codeType.getParamNameOnValidate());
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException(codeType + "验证码的值不能为空");
        }

        if (codeInSession == null) {
            throw new ValidateCodeException(codeType + "验证码不存在");
        }

        if (codeInSession.isExpried()) {
            validateCodeRepository.remove(request, codeType);
            throw new ValidateCodeException(codeType + "验证码已过期");
        }

        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException(codeType + "验证码不匹配");
        }

        validateCodeRepository.remove(request, codeType);
    }

    private void save(ServletWebRequest request,C validateCode) {
        ValidateCode code = new ValidateCode(validateCode.getCode(), validateCode.getExpireTime());
        validateCodeRepository.save(request,code,this.getValidateCodeType(request));
    }

    private C generate(ServletWebRequest request) {
        String type = this.getValidateCodeType(request).toString().toLowerCase();
        String generatorName = type + ValidateCodeGenerator.class.getSimpleName();
        ValidateCodeGenerator validateCodeGenerator = validateCodeGeneratorMap.get(generatorName);
        if (validateCodeGenerator == null) {
            throw new ValidateCodeException("代码生成器:" + generatorName + "不存在");
        }
        return (C) validateCodeGenerator.createCode(request);
    }

    private ValidateCodeType getValidateCodeType(ServletWebRequest request) {
        String type = StringUtils.substringBefore(getClass().getSimpleName(), "codeProcessor");
        return ValidateCodeType.valueOf(type.toUpperCase());
    }
    /*发送校验码，由子类实现*/
    protected abstract void send(ServletWebRequest request, C validateCode) throws Exception;


}